package com.etoak.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.redis.RedisService;
import com.etoak.vo.CodeVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    RedisService redisService;

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @GetMapping("/getCode")
    public ResultVO<CodeVO> getCode() throws IOException {
        // kaptchaText = 1+1=?@2
        String kaptchaText = defaultKaptcha.createText();

        // kaptchaTextArray = [1+1=?, 2]
        String[] kaptchaTextArray = kaptchaText.split(StrUtil.AT);

        /* 将验证码结果写入Redis, 默认5分钟有效
        *  redis kay = code:uuid的值
        *  redis value = kaptchaTextArray[1]
        * */
        String uuid = IdUtil.simpleUUID();
        String redisKey = CommonConstant.REDIS_CODE_PREFIX + uuid;
        String redisValue = kaptchaTextArray[1];
        redisService.setex(redisKey, redisValue, 5, TimeUnit.MINUTES);

        /* 创建验证码图片 */
        BufferedImage kaptchaImage = defaultKaptcha.createImage(kaptchaTextArray[0]);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(kaptchaImage, "png", outputStream);

        /* 生成Base64编码(3字节 => 4字节) */
        byte[] byteArray = outputStream.toByteArray();
        String base64 = Base64.encode(byteArray);
        String codeUrl = "data:image/png;base64," + base64;
        CodeVO codeVO = new CodeVO(codeUrl, uuid);
        return ResultVO.success(codeVO);
    }
}
